/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By zhanglin
* 注意：
* 本软件为zhanglin开发研制
 */
package model

import (
	"shop/global"
)

type IUsersRoles interface {
	InsertUsersRoles() (int64, error)
	DeleteUsersRoles(userId int64) error
	UpdateUsersRoles() error
	FindUsersRolesList() (interface{}, error)
	SplitPageUsersRolesList(pageIndex int64, pageSize int64) (interface{}, error)
}

/**
	UsersRoles实体对象
 **/
type UsersRoles struct {
	UserId int64 `json:"user_id" gorm:"primary_key"` //用户ID

	RoleId int64 `json:"role_id"` //角色ID
}

func (vo *UsersRoles) InsertUsersRoles() (int64, error) {
	table := global.GDB.Table("users_roles")
	if err := table.Create(&vo).Error; err != nil {
		return 0, err
	}

	return vo.UserId, nil
}

func (vo *UsersRoles) DeleteUsersRoles(userId int64) error {
	table := global.GDB.Table("users_roles")
	table = table.Where("user_id = ?", userId)
	if err := table.Delete(UsersRoles{}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *UsersRoles) UpdateUsersRoles() error {

	table := global.GDB.Table("users_roles")
	table = table.Where("user_id = ?", vo.UserId)
	if err := table.Updates(map[string]interface{}{
		"user_id": vo.UserId, "role_id": vo.RoleId}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *UsersRoles) FindUsersRolesList() ([]UsersRoles, error) {
	var lists []UsersRoles
	table := global.GDB.Table("users_roles")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func (vo *UsersRoles) SplitPageUsersRolesList(pageIndex int64, pageSize int64) (interface{}, error) {
	var lists []UsersRoles
	var total int64
	table := global.GDB.Table("users_roles")
	table = table.Select("  user_id,   role_id   ")
	if err := table.Count(&total).Error; err != nil {
		return lists, err
	}
	table = table.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}

	m := make(map[string]interface{})
	m["lists"] = lists
	m["total"] = total
	return m, nil
}
